
#include "ping.h"

#include <errno.h>
#include <signal.h>

void readloop() {

    int size;
    char recvbuffer[BUFFER_SIZE];
    char controlbuf[BUFFER_SIZE];

    struct msghdr msg;
    struct iovec  iov;

    ssize_t n;
    struct timeval tval;

    Instance()->sockfd = socket(Instance()->pr->sasend->sa_family, SOCK_RAW, Instance()->pr->icmpproto);

    printf("Instance() : sockfd = %d\n", Instance()->sockfd);

    int bsize = 1024 * 200;
    setsockopt(Instance()->sockfd, SOL_SOCKET, SO_RCVBUF, &bsize, sizeof(bsize));

    sig_alarm(SIGALRM);

    iov.iov_base = recvbuffer;
    iov.iov_len  = BUFFER_SIZE;

    msg.msg_name = Instance()->pr->sarecv;
    msg.msg_iov  = &iov;
    msg.msg_iovlen = 1;
    msg.msg_control = controlbuf;
    for (; ; ) {

        msg.msg_namelen = Instance()->pr->salen;
        msg.msg_controllen = sizeof(controlbuf);

        n = recvmsg(Instance()->sockfd, &msg, 0);
        if (n < 0) {

            if (errno == EINTR) {

                continue;
            } else {

                printf("recvmsg error %d\n", errno);
                exit(4);
            }
        }
        // process message
        gettimeofday(&tval, NULL);
        Instance()->pr->fptoc(recvbuffer, n, &msg, &tval);
    }
}